﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Sys.WebRes.Data;
using Sys.WebRes.Publish.Areas.Admin.Models;
using System.Collections;

namespace Sys.WebRes.Publish.Areas.Admin.Controllers
{
    public class SectionController : Controller
    {
        /// <summary>
        /// 栏目列表画面
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        } 

        /// <summary>
        /// 栏目列表
        /// </summary>
        /// <returns>JSON</returns>
        public ActionResult List()
        {
            IList result = null;
            using (var db = new ResourceSysEntities())
            {
                var map = db.SectionTBL.Where(p => p.DeletedFlag == false)
                                        .OrderBy(p => p.OrderNo)
                                        .Select(p => new SectionModel{
                                            ID = p.ID,
                                            Name = p.Name,
                                            Abbr = p.Abbr,
                                            Summary = p.Summary,
                                            OrderNo = p.OrderNo,
                                            ParentID = (int?)p.Parent.ID,
                                            ResTypeID = p.ResType.ID,
                                            StatusTypeID = p.StatusType.ID,
                                            LevelNo = p.LevelNo,
                                            Visible = p.Visible})
                                        .ToDictionary(k => k.ID, v => v);


                var list = new List<SectionModel>();
                foreach (var item in map)
                {
                    if (item.Value.ParentID != null)
                    {
                        int key = item.Value.ParentID ?? 0;
                        map[key].children.Add(item.Value);
                    }
                    else
                    {
                        list.Add(item.Value);
                    }
                }

                result = list;
            }

            return this.Json(result, JsonRequestBehavior.AllowGet);
        }
        
        /// <summary>
        /// 开始编辑栏目
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Edit(int? id)
        {
            if (id <= 0)
            {
                return View();
            }
            using (var db = new ResourceSysEntities())
            {
                var model = db.SectionTBL.Where(p => p.ID == id && p.DeletedFlag == false)
                                         .Select(p => new SectionModel{
                                            ID = p.ID,
                                            Name = p.Name,
                                            Abbr = p.Abbr,
                                            Summary = p.Summary,
                                            OrderNo = p.OrderNo,
                                            ParentID = (int?)p.Parent.ID,
                                            ResTypeID = p.ResType.ID,
                                            StatusTypeID = p.StatusType.ID,
                                            LevelNo = p.LevelNo,
                                            Visible = p.Visible})
                                         .FirstOrDefault();
                if (model == null)
                {
                    model = new SectionModel();
                }

                return View(model);
            }
        }

        /// <summary>
        /// 编辑栏目
        /// </summary>
        /// <param name="id"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(int id, SectionModel model)
        {
            if (id <= 0)
            {
                Create(model);
            }
            else
            {
                using (var tran = DB.NewTran)
                {
                    using (var db = DB.New)
                    {
                        var section = db.SectionTBL.FirstOrDefault(p => p.DeletedFlag == false && p.ID == id);

                        if (section != null)
                        {
                            if (model.DeletedFlag == false)
                            {
                                //this.TryUpdateModel(section, null, null, new string[] { "Children" });
                                section.CopyFrom(model);
                                section.ResType = db.ResTypeTBL.FirstOrDefault(p => p.ID == model.ResTypeID);
                                section.StatusType = db.ResStatusTypeTBL.FirstOrDefault(p => p.ID == model.StatusTypeID);
                                section.Parent = (model.ParentID == null) ? null : db.SectionTBL.FirstOrDefault(p => p.ID == model.ParentID);
                            }
                            else
                            {
                                section.DeletedFlag = true;
                            }
                            db.SaveChanges();
                        }
                    };
                    tran.Complete();
                }
            }

            return View(model);
        }

        /// <summary>
        /// 创建一个栏目
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        private bool Create(SectionModel model)
        {
            using (var tran = DB.NewTran)
            {
                var section = new Section();
                using (var db = DB.New)
                {
                    //this.TryUpdateModel(section, null, null, new string[] { "Children" });
                    section.CopyFrom(model);
                    section.Language = db.LanguageTBL.FirstOrDefault(p => p.ID == 1);
                    section.ResType = db.ResTypeTBL.FirstOrDefault(p => p.ID == model.ResTypeID);
                    section.StatusType = db.ResStatusTypeTBL.FirstOrDefault(p => p.ID == model.StatusTypeID);
                    if (model.ParentID != null)
                    {
                        section.Parent = db.SectionTBL.FirstOrDefault(p => p.ID == model.ParentID);
                    }

                    section.ID = (db.SectionTBL.Max<Section, int?>(p => p.ID) ?? 0) + 1;
                    db.AddToSectionTBL(section);
                    db.SaveChanges();
                }
                model.ID = section.ID;
                tran.Complete();

                return true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Delete(string[] ids)
        {
            try
            {
                using (var db = new ResourceSysEntities())
                {
                    string csvIds = string.Join(",", ids.Cast<string>().ToArray());

                    db.SectionTBL.Where("it.ID in {"+csvIds+"}").Where(p=>p.Children.FirstOrDefault() == null && p.DeletedFlag == false)
                                 .ToList().ForEach(p=>p.DeletedFlag = true);

                    //db.SectionTBL.Where(p => ids.Any(a=>a==p.ID) && p.Children.FirstOrDefault() == null && p.DeletedFlag == false)
                    //             .ToList().ForEach(p=>p.DeletedFlag = true);

                    db.SaveChanges();

                    return Json(new { result = true }, JsonRequestBehavior.AllowGet);
                }
            }
            catch
            {
                return Json(new { result = false }, JsonRequestBehavior.AllowGet);
            }
        }
    }
}
